﻿using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace PlaxoSyncWM {
    public class PlaxoLogin {
        private HttpWebRequest req;
        private HttpWebResponse resp = null;
        private StreamReader reader;
        public Settings settings;

        public string[] getPlaxoSettings() {
            settings = new Settings();
            string[] plaxoSettings = new string[3];
            plaxoSettings.SetValue(settings.GetSetting("username"), 0);
            plaxoSettings.SetValue(settings.GetSetting("password"), 1);
            plaxoSettings.SetValue(settings.GetSetting("GUID"), 2);
            return plaxoSettings;
        }

        public bool checkAccount() {
            bool check = false;
            string url = GetUrl();
            ServicePointManager.CertificatePolicy = new CertPolicy();
            req = (HttpWebRequest) HttpWebRequest.Create(url);
            resp = (HttpWebResponse) req.GetResponse();
            Regex splitOnRegX = new Regex(@",", RegexOptions.Compiled);
            if (resp.StatusCode == HttpStatusCode.OK) {
                string line;

                reader = new StreamReader(resp.GetResponseStream());
                while ((line = reader.ReadLine()) != null) {
                    string[] elements = splitOnRegX.Split(line);
                    if (line.Contains("Code")) {
                        if (elements[4].Equals(" '200'"))
                            check = true;
                    }
                }
            }
            resp.Close();
            req.Abort();
            return check;
        }

        private string GetUrl() {
            string[] plaxoSettings = getPlaxoSettings();
            string username = string.Format(@"'{0}'", plaxoSettings[0]);
            string password = string.Format(@"'{0}'", plaxoSettings[1]);
            string GUID = plaxoSettings[2];
            return
                string.Format(
                    @"https://testapi.plaxo.com/rest?package=['Header', 'ProtoVer', '1', 'ClientID', {0}, 'Identifier',{1},
                                        'AuthMethod', 'Plaxo', 'Password',{2}, 'Client', 'Dev Clientname/1.0', 'OS', 'windows/service pack infinity',
                                        'Platform', 'Outlook/2005']%0a['/Header']",
                    GUID, username, password);
        }

        internal static void showStatus(string p) {}
    }
}